package cn.blu10ph.tools.web_ctrl;

import fi.iki.elonen.NanoHTTPD;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.JarFile;

public class HttpServer extends NanoHTTPD {
    public HttpServer() {
        super(19091);
    }

    public HttpServer(int port) {
        super(port);
    }

    @Override
    public Response serve(IHTTPSession session) {
        InputStream inputStream;
        File file;
        Response response = null;
        String uri = session.getUri();
        System.out.println("uri:" + uri);

        try {
            URL url = this.getClass().getResource("/");
            String resourcePath = url.getFile();
            System.out.println("resourcePath:" + resourcePath);

            file = new File(resourcePath + "../resources" + uri);
            System.out.println("file:" + file.getPath());
            if (file.exists() && file.isDirectory()) {
                file = new File(resourcePath + "../resources/" + "index.html");
                System.out.println("file:" + file.getPath());
            }
            if (file.exists()) {
                inputStream = new FileInputStream(file);
                response = newChunkedResponse(Response.Status.OK, "text/html", inputStream);//这代表任意的二进制数据传输。
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            response = null;
        }

        if (response == null) {
            try {
                System.out.println("uri.charAt(uri.length()-1):" + uri.charAt(uri.length()-1));
                if(new Character('/').equals(uri.charAt(uri.length()-1))){
                    uri = uri + "index.html";
                    System.out.println("uri:" + uri);
                }

                inputStream = this.getClass().getResourceAsStream(uri);
                response = newChunkedResponse(Response.Status.OK, "text/html", inputStream);//这代表任意的二进制数据传输。
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        if (response == null) {
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html><html><body>");
            builder.append("404 -- Sorry, Can't Found " + uri + " !");
            builder.append("</body></html>\n");
            response = newFixedLengthResponse(Response.Status.NOT_FOUND, "text/html", builder.toString());//这代表任意的二进制数据传输。
        }

        return response;
    }
}
